package com.aube.interact;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.aube.interact.controller.AbstractController;
import com.aube.interact.controller.CardsController;
import com.aube.interact.controller.DataManager;
import com.aube.interact.model.GoodsItem;
import com.aube.interact.model.OptionItem;
import com.aube.interact.model.ReportResultModel;
import com.aube.interact.model.TimeLinePiece;
import com.aube.rvi.CommonDataLoader;
import com.aube.rvi.net.AubeError;
import com.aube.rvi.net.ResponseListener;
import com.aube.rvi.net.StringRequest;
import com.aube.rvi.util.StringUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by huyaonan on 16/3/23.
 */
public abstract class BaseCardNew extends LinearLayout implements CardsController.IDataSyncHelper {

    protected static final String TYPE_PIC = "PIC";
    protected static final String TYPE_QA = "QA";
    protected static final String TYPE_VOTE = "VOTE";
    protected static final String TYPE_PK = "PK";

    protected IDataSyncSender iSender;

    protected TimeLinePiece mData;
    protected String mVideoId;

    protected int mContentHeight = 0;
    protected int mMinHeight = 0;

    protected ImageView mCollapse;

    public BaseCardNew(Context context) {
        this(context, null);
    }
    public BaseCardNew(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public BaseCardNew(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //do nothing
            }
        });
    }

    public void init(TimeLinePiece data, String mVideoId) {
        this.mData = data;
        this.mVideoId = mVideoId;
    }

    public abstract String getType();

    public void updateCountDown(String time) {

    }

    public void setupSender(IDataSyncSender iSender) {
        this.iSender = iSender;
        doNext();
    }

    public void doNext() {}

    public interface IDataSyncSender {
        public void startSync(String id, boolean oneTime);
        public void postResult(String id, List<OptionItem> results, String cancelId, String selectedId);
        public void close();
        public void onAddRewardGoods(List<GoodsItem> data);
    }

    public void close() {
        if(iSender != null)
            iSender.close();
    }

    public void removeSender() {
        iSender = null;
    }

    public void clearData() {

    }

    public void report(String rid, String msg, List<GoodsItem> goodsItemList) {

    }

    public void report(final String rid, final String optionId, final String cancelId, final boolean reportResult) {
        clearData();
        HashMap<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("rid", rid);
        if(StringUtils.isNotBlank(cancelId))
            parameterMap.put("cancelOpId", cancelId);
        if(StringUtils.isNotBlank(optionId) && !optionId.equalsIgnoreCase(cancelId))
            parameterMap.put("optionId", optionId);
        parameterMap.put("type", getType());

        //保存
        DataManager.getInstance(getContext()).updateSelectedOptionId(rid, optionId);

        parameterMap.put("method", "com.aube.video.interact.reportData");
        StringRequest request = new StringRequest(AbstractController.API_ROUTER, parameterMap, new ResponseListener<String>() {

            @Override
            public void onResponse(String result) {
                if(result != null) {
                    //parse response
                    ReportResultModel response = ReportResultModel.parse(result);
                    report(optionId, response.getMessage(), response.getGoodsList());

                    if (reportResult && iSender != null) {
                        iSender.postResult(rid, response.getOptions(), cancelId, optionId);
                    }
                }
            }

            @Override
            public void onErrorResponse(AubeError error) {
            }

            @Override
            public void onStart() {
            }
        });
        CommonDataLoader.getInstance(getContext()).startHttpLoader(request);
    }

    public String appendPercentStr(int value) {
//        return "<font><small>&nbsp;" + value + "%</small></font>";
        return value+"%";
    }


    protected void swithWindow(boolean toCollapse, View mGroup) {
        if(!toCollapse) {
            mCollapse.setImageResource(R.drawable.icon_arrowdown);
//            mGroup.setVisibility(View.GONE);
        } else {
            mCollapse.setImageResource(R.drawable.icon_arrowup);
//            mGroup.setVisibility(View.VISIBLE);
        }
        animGroup(!toCollapse, mGroup);
    }

    private static final int DURATION = 200;
    protected void animGroup(final boolean animDown, final View mGroup) {
        float startValue = animDown ? mMinHeight : mContentHeight;
        float endValue = animDown ? mContentHeight : mMinHeight;
        final ValueAnimator anim = ValueAnimator.ofFloat(startValue, endValue);
        anim.setDuration(DURATION);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();

                LayoutParams params = (LayoutParams) mGroup.getLayoutParams();
                params.height = (int) value;
                mGroup.setLayoutParams(params);
            }
        });
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                if (animDown) {
                    mGroup.setAlpha(0);
                    mGroup.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if (!animDown)
                    mGroup.setVisibility(View.INVISIBLE);
            }
        });

        AnimatorSet set = new AnimatorSet();
        Animator alphaAnim = ObjectAnimator.ofFloat(mGroup, "alpha", animDown ? 0 : 1, animDown ? 1 : 0);
        alphaAnim.setDuration(DURATION);

        if(animDown) {
            set.playSequentially(anim, alphaAnim);
        } else {
            set.playSequentially(alphaAnim, anim);
        }
        set.start();
    }

    public void reSortData(HashMap<String, Integer> mSet) {
        String maxId="";
        int max = 0;
        int total = 0;
        Iterator<Map.Entry<String, Integer>> iterator = mSet.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Integer> entry = iterator.next();
            total += entry.getValue();
            if(entry.getValue() > max) {
                max = entry.getValue();
                maxId = entry.getKey();
            }
        }

        if(total > 100) {
            int value = mSet.get(maxId);
            mSet.put(maxId, value + 100 - total);
        }
    }

    /**
     * TODO
     * 绝对定位
     * @param width
     * @param height
     */
    protected void locateView(int width, int height) {

    }

    public void animIn(RelativeLayout parent, Animation.AnimationListener listener) {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//        params.addRule(RelativeLayout.CENTER_VERTICAL);
        params.addRule(RelativeLayout.CENTER_HORIZONTAL);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        parent.addView(this, params);

        System.out.println("---------size:" + getMeasuredWidth() + "/" + getMeasuredHeight());

//        setTranslationX(500);
//        setTranslationY(500);

        Animation anim = AnimationUtils.loadAnimation(getContext(), R.anim.push_bottom_in);
        anim.setAnimationListener(listener);
        startAnimation(anim);
    }

    public void animOut(Animation.AnimationListener listener) {
        Animation anim = AnimationUtils.loadAnimation(getContext(), R.anim.card_out);
        anim.setAnimationListener(listener);
        startAnimation(anim);
    }

    public interface IAubeAnimListener {
        public void onStart();
        public void onEnd();
    }

}
